package com.py.credit.service.impl;

import com.py.credit.dao.EvalInfoDao;
import com.py.credit.dao.ModelBaseDao;
import com.py.credit.dao.UserEvaInfoDao;
import com.py.credit.entity.Cards;
import com.py.credit.entity.DictDetailEntity;
import com.py.credit.service.*;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.FileUtil;
import com.py.credit.utils.UuidUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Company: WWW.xypy.com.cn
 * @ClassName UserEvaInfoServiceImpl
 * @Description: 信用评价申报业务层实现类
 * @Params: Test
 * @Author: YaoS
 * @Create: 2018-10-24 11:31
 **/
@Service
public class UserEvaInfoServiceImpl implements UserEvaInfoService {
    private static final String CATEGORY = "category";
    private static final String INDEX = "index";
    private static final String INDEX_LIST = "indexList";
    private static final String CATEGORY_LIST = "categorylist";
    private static final String CATEGORY_DETAIL = "categoryDetail";
    private static final String TWO = "2";
    private static final String FOUR = "4";
    @Autowired
    UserEvaInfoDao userEvaInfoDao;

    @Autowired
    ModelBaseDao modelBaseDao;

    @Autowired
    EvalInfoDao evalInfoDao;

    @Autowired
    EvalInfoService evalInfoService;

    @Autowired
    XypjRemoteBaseService xypjRemoteBaseService;

    @Autowired
    SysDictService sysDictService;
    @Autowired
    CardsService cardsService;

    @Autowired
    IndexService indexService;

    @Override
    public String selectAllTable(String zone, String industry, String reportType) {
        //查询modelId
        String modelId = userEvaInfoDao.selectModel(zone, industry, reportType);
        return modelId;
    }

    @Override
    public String selectStatusByModel(String sqr, String modelId) {
        return userEvaInfoDao.selectStatusByModel(sqr, modelId);
    }

    @Override
    public ArrayList<Map<String, Object>> selectIndexOrCategroy(String modelId, String sqr, String evainfoId) {
        //存放指标list
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        List<String> indexId = null;
        ArrayList<Map<String, Object>> listOne = userEvaInfoDao.selectCategoryOnModel(modelId, sqr);
        if (!("").equals(evainfoId) && null != evainfoId) {
            indexId = userEvaInfoDao.getReturnIndexId(evainfoId);
        }
        for (Map<String, Object> node : listOne) {
            //如果是category
            if (CATEGORY.equals(node.get("type"))) {
                list.add(node);
            } else if (INDEX.equals(node.get("type"))) {
                if (TWO.equals(node.get("inputType")) || FOUR.equals(node.get("inputType"))) {
                    //获取指标的dictSource
                    String dictSource = (String) node.get("dictSource");
                    //获取所有下拉框字典值
                    List returnList = new ArrayList();
                    List<DictDetailEntity> selectList = sysDictService.getDictDetails(dictSource, StringUtils.EMPTY);
                    for (DictDetailEntity d : selectList) {
                        Map<String, String> dmap = new HashMap<>();
                        dmap.put(d.getDtlKey() + "", d.getDtlValue());
                        returnList.add(dmap);
                    }
                    node.put("selectList", returnList);
                }
                if (null != indexId) {
                    int size = indexId.size();
                    for (int i = 0; i < size; i++) {
                        if (node.get("indexOrCatId").equals(indexId.get(i))) {
                            node.put("flag", 1);
                        }
                    }
                }
                if (node.get("type1").equals("6")) {
                    Cards cards = cardsService.selectCardsDetail(null, null, (String) node.get("inputType"), sqr, "2");
                    if(null != cards) {
                    	node.put("path", cards.getId());	
                    }
                }
                String callType = (String) node.get("callType");
                if (callType != null) {
                    if (node.get("callType").equals("2")) {
                        String value = indexService.selectDataBycolmunEN((String) node.get("treeElem"), sqr);
                        node.put("callContent", value);
                    }
                }

                //指标list添加一个指标
                list.add(node);
            }
        }
        return list;
    }


    @Transactional
    @Override
    public void insertIndexTable(List<Map<String, String>> list, String userName, String userId, String modelId, String orgId) {
        List list1 = new ArrayList();
        String uuid = UuidUtil.getUUid();
        for (Map<String, String> map : list) {
            map.put("id", UuidUtil.getUUid());
            map.put("userName", userName);
            map.put("userId", userId);
            map.put("evainfoId", uuid);
            list1.add(map);
        }
        userEvaInfoDao.insertIndex(list1);
        Map m = modelBaseDao.selectOne(modelId);
        m.put("uuid", uuid);
		Map<String,String> mCheck=modelBaseDao.selectCheckProcessForOrg(orgId, modelId);
		String checkProcess=mCheck.get("checkProcess");
		if(StringUtils.isBlank(checkProcess)){
			checkProcess = evalInfoDao.getCheckProcessByModel(modelId);
		}
        //String checkProcess = evalInfoDao.getCheckProcessByModel(modelId);
        String checkType = String.valueOf(m.get("checkType") == null ? "" : m.get("checkType"));
        String newStatus = "";
        if ("1".equals(checkType)) {
            newStatus = "00";
        } else {
            int index = Integer.parseInt("0");
            for (int i = index; i < checkProcess.length(); i++) {
                if (checkProcess.charAt(i) == '1') {
                    newStatus = String.valueOf(i + 1);
                    break;
                }
            }
        }
        evalInfoDao.evalProcess(UuidUtil.getUUid(), "0", newStatus, userId, new Date(), "", uuid);
        m.put("sqr", userId);
        m.put("orgId", orgId);
        m.put("newstatus", newStatus);
        m.put("slbh", userEvaInfoDao.getSlbh());
        m.put("bgbh", userEvaInfoDao.getBgbh(String.valueOf(m.get("bm")), modelId));
        userEvaInfoDao.insertEvalInfo(m);
        if ("1".equals(checkType)||"3".equals(newStatus)) {
            evalInfoService.preScore(modelId, userId, uuid);
        }
    }

    @Override
    public void fileUpload(MultipartFile file, String pathFile)
            throws IllegalStateException, IOException {
        File uploadFile = null;
        File dirPath = new File(pathFile);
        uploadFile = new File(pathFile + File.separator + file.getOriginalFilename());
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try {
            file.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void fileDownload(String path, HttpServletRequest request, HttpServletResponse response) {
//        String path = "";
        FileUtil.uploadFile(path, request, response);
    }

    @Override
    public Integer selectOrgAndModel(String reportType, String orgId) {

        return userEvaInfoDao.selectOrgAndModel(reportType, orgId);
    }

    @Override
    public void updateDelFlag(String evalinfoId) {

        userEvaInfoDao.updateDelFlag(evalinfoId);
    }

    @Override
    public List<Map> viewCheck(String modelId, String sqr, String evainfoId) {
        return null;
    }

    @Override
    public List selectReport(String zone,String scoreType, String industry) {
        return userEvaInfoDao.selectReport(zone,scoreType, industry);
    }

	@Override
	public Integer selectExistReport(String modelId, String orgId, String sqr) {
		
		return userEvaInfoDao.selectExistReport(modelId, orgId, sqr);
	}
}